//
//  AuthenSetRateVC.swift
//  kxf
//  商户进件，需要设置费率（代理商帮忙进件，富友通道需要设置）
//  Created by Elavatine on 2024/10/6.
//

import MCToast

class AuthenSetRateVC: WHBaseViewVC {
    
    var phone = ""
    
    var dataArr = NSArray()
    var channelListArray = NSArray()
    var channel = "fy"
    
    var dataSubmitArray = NSMutableArray()
    
    var vmDataArray = NSMutableArray()
    
    var param = NSDictionary()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        initUI()
        getRateInfoRequest()
        vmScrollView.frame = CGRect.init(x: 0, y: getNavigationBarHeight()+kFitWidth(10), width: SCREEN_WIDHT, height: SCREEN_HEIGHT-getBottomSafeAreaHeight()-getNavigationBarHeight()-kFitWidth(20))
        view.addSubview(vmScrollView)
        vmScrollView.addSubview(nextBtn)
    }
    
    lazy var vmScrollView: UIScrollView = {
        let scro = UIScrollView(frame: CGRect.init(x: 0, y: getNavigationBarHeight()+kFitWidth(1), width: SCREEN_WIDHT, height: SCREEN_HEIGHT-getBottomSafeAreaHeight()))
        
        return scro
    }()
    lazy var nextBtn : UIButton = {
        let btn = UIButton()
        btn.setTitle("确认", for: .normal)
        btn.setTitleColor(.white, for: .normal)
        btn.setBackgroundImage(UIImage.init(named: "button_theme_bg"), for: .normal)
        btn.layer.cornerRadius = kFitWidth(24)
        btn.clipsToBounds = true
        btn.titleLabel?.font = .systemFont(ofSize: 16, weight: .regular)
        btn.backgroundColor = .clear
        
        btn.addTarget(self, action: #selector(submitAction), for: .touchUpInside)
        
        return btn
    }()
}

extension AuthenSetRateVC{
    @objc func submitAction(){
        if checkValue(){
            sendSetRateInfoRequest()
        }
    }
    func checkValue() -> Bool {
        dataSubmitArray = NSMutableArray()
        for i in 0..<vmDataArray.count {
            let vm = vmDataArray[i]as! SetRateMsgItemVM
            let feeNum = vm.feeTextField.text
            let extraNum = vm.extraTextField.text
            
            if feeNum?.floatValue ?? 0 == 0 || feeNum == ""{
                MCToast.mc_text("\(vm.leftTitleLabel.text ?? "")费率不能为空")
                return false
            }
            let dictT = dataArr[i]as? NSDictionary ?? [:]
            
            if feeNum?.floatValue ?? 0 > Float(dictT["channelRateMax"]as? Double ?? 0.00) || feeNum?.floatValue ?? 0 < Float(dictT["channelRateMin"]as? Double ?? 0.00){
                MCToast.mc_text("\(vm.leftTitleLabel.text ?? "")费率范围 \(vm.feeAreaLabel.text ?? "")")
                return false
            }
            
            if extraNum?.floatValue ?? 0 > Float(dictT["channelSettlementMax"]as? Double ?? 0.00) || extraNum?.floatValue ?? 0 < Float(dictT["channelSettlementMin"]as? Double ?? 0.00){
                MCToast.mc_text("\(vm.leftTitleLabel.text ?? "")手续费范围 \(vm.extraAreaLabel.text ?? "")")
                return false
            }
            
            let dict = NSMutableDictionary.init(dictionary: dictT)
            dict.setValue("\(feeNum ?? "")", forKey: "channelRate")
            dict.setValue("\(extraNum ?? "")", forKey: "channelSettlement")
            dict.setValue("\(dictT["productName"]as? String ?? "")", forKey: "channel")
            dict.setValue(false, forKey: "showFee")
            dict.setValue(false, forKey: "showLement")
            dict.setValue(false, forKey: "showRate")
            dict.setValue("\(Float(dictT["channelRateMin"]as? Double ?? 0))", forKey: "channelRateMin")
            dict.setValue("\(Float(dictT["channelRateVip"]as? Double ?? 0))", forKey: "channelRateVip")
            dict.setValue("\(Float(dictT["channelRateMax"]as? Double ?? 0))", forKey: "channelRateMax")
            dict.setValue("\(Float(dictT["channelRateDefault"]as? Double ?? 0))", forKey: "channelRateDefault")
            dict.setValue("\(Float(dictT["channelD0Rate"]as? Double ?? 0))", forKey: "channelD0Rate")
            dict.setValue("\(Float(dictT["channelRealD0Rate"]as? Double ?? 0))", forKey: "channelRealD0Rate")
            dict.setValue("\(Float(dictT["channelSettlementMin"]as? Double ?? 0))", forKey: "channelSettlementMin")
            dict.setValue("\(Float(dictT["channelSettlementMax"]as? Double ?? 0))", forKey: "channelSettlementMax")
            dict.setValue("\(Float(dictT["channelSettlementVip"]as? Double ?? 0))", forKey: "channelSettlementVip")
            dict.setValue("\(Float(dictT["channelD0RateMin"]as? Double ?? 0))", forKey: "channelD0RateMin")
            dict.setValue("\(Float(dictT["channelD0RateMax"]as? Double ?? 0))", forKey: "channelD0RateMax")
            dict.setValue("\(Float(dictT["feeTop"]as? Double ?? 0))", forKey: "feeTop")
            dict.setValue("\(Float(dictT["feeMin"]as? Double ?? 0))", forKey: "feeMin")
            dict.setValue("\(Float(dictT["feeMax"]as? Double ?? 0))", forKey: "feeMax")
            dict.setValue("\(Float(dictT["startAmount"]as? Double ?? 0))", forKey: "startAmount")
            dict.setValue("\(Float(dictT["endAmount"]as? Double ?? 0))", forKey: "endAmount")
            
            dataSubmitArray.add(dict)
        }
        return true
    }
}
extension AuthenSetRateVC{
    func initUI() {
        initNavi(titleStr: "设置费率")
        view.backgroundColor = .COLOR_LIGHT_GREY
        
    }
    func refreshUI() {
        for vi in vmScrollView.subviews{
            if vi.isKind(of: SetRateMsgItemVM.self){
                vi.removeFromSuperview()
            }
        }
        
        vmDataArray.removeAllObjects()
        
        let originY = kFitWidth(10)
        for i in 0..<dataArr.count{
            let dict = dataArr[i]as? NSDictionary ?? [:]
            let vm = SetRateMsgItemVM.init(frame: CGRect.init(x: 0, y: originY+SetRateMsgItemVM().selfHeight*CGFloat(i), width: 0, height: 0))
            vmScrollView.addSubview(vm)
            vm.refreshUI(dict: dict,isMerc:false)
            vm.tag = 3070 + i
//            vm.refreshUIForMerc()
            vmDataArray.add(vm)
        }
        vmScrollView.contentSize = CGSize.init(width: 0, height: originY+SetRateMsgItemVM().selfHeight*CGFloat(dataArr.count)+kFitWidth(20))
        nextBtn.frame = CGRect.init(x: kFitWidth(31), y: originY+SetRateMsgItemVM().selfHeight*CGFloat(dataArr.count)+kFitWidth(68), width: kFitWidth(316), height: kFitWidth(48))
        vmScrollView.contentSize = CGSize.init(width: 0, height: originY+SetRateMsgItemVM().selfHeight*CGFloat(dataArr.count)+kFitWidth(130))
    }
}

extension AuthenSetRateVC{
    func getRateInfoRequest() {
        MCToast.mc_loading()
        let urlString = "\(URL_get_pos_rateTemplate)?phone=\(phone)&type=0&posChannel=fy"
        WHNetworkUtil.shareManager().GET(urlString: urlString) { response in
            DLLog(message: "\(response)")
            MCToast.mc_remove()
            let dataDict = response["data"]as? NSDictionary ?? [:]
            self.dataArr = dataDict["list"]as? NSArray ?? []
            self.refreshUI()
        }
    }
    func sendSetRateInfoRequest() {
        let type = "0"
        let param = ["list":dataSubmitArray,
                     "phone":"\(phone)",
                     "type":"\(type)",
                     "freezeAmount":"0",
                     "channel":"\(self.channel)"] as [String : Any]
        WHNetworkUtil.shareManager().POST(urlString: URL_modify_pos_rate, parameters: param as [String : AnyObject],isNeedToast: true,vc: self) { responseObject in
            DLLog(message: "\(responseObject)")
            MCToast.mc_text("费率设置成功！")
            self.sendCertRequest()
        }
    }
    //入网
    func sendCertRequest() {
        MCToast.mc_loading()
        let paramDict = NSMutableDictionary.init(dictionary: param)
        paramDict.setValue("0", forKey: "type")
        WHNetworkUtil.shareManager().POST(urlString: URL_authen_user_cert, parameters: paramDict as? [String : AnyObject],isNeedToast: true,vc: self) { responseObject in
            DLLog(message: "\(responseObject)")
            MCToast.mc_remove()
            if responseObject["code"]as? Int ?? 0 == 200{
                AuthenMiniMsgModel.shareInstance.clearMsg()
                self.presentAlertVc(confirmBtn: "确定", message: "", title: "提交成功，请等待审核。", cancelBtn: nil, handler: { action in
                    self.navigationController?.popToRootViewController(animated: true)
                }, viewController: self)
            }else{
                self.presentAlertVcNoAction(title: "\(responseObject["message"]as? String ?? "保存失败!")", viewController: self)
            }
        }
    }
}
